package com.bingxue.edu.management.auth.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.bingxue.edu.framework.common.util.ValidationUtils;
import com.bingxue.edu.management.auth.model.req.UserBasicInfoUpdateReq;
import com.bingxue.edu.management.system.model.entity.Employee;
import com.bingxue.edu.management.system.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmployeeUserCenterService {

    private final EmployeeService employeeService;

    /**
     * 用户中心修改基础信息
     * @param req
     * @param currentUserId
     */
    public void updateBasicInfo(UserBasicInfoUpdateReq req, String currentUserId) {
        Employee employee = employeeService.copy(req);
        employee.setId(currentUserId);
        employeeService.updateById(employee);
    }

    /**
     * 个人中心修改密码
     *
     * @param newPassword
     * @param currentUserId
     */
    public void updatePassword(String oldPassword, String newPassword, String currentUserId) {
        Employee employee = employeeService.getById(currentUserId);
        boolean isError = ObjectUtil.isNull(employee) || !DigestUtil.bcryptCheck(oldPassword, employee.getPassword());
        ValidationUtils.throwIf(isError, "原密码错误");
        employee.setPassword(DigestUtil.bcrypt(newPassword));
        employee.setLastPwdModifiedTime(LocalDateTime.now());
        employeeService.updateById(employee);

        log.info("更新员工个人密码成功, {}, {}", currentUserId, newPassword);
    }

    /**
     * 个人中心修改电话
     * @param newPhone
     * @param oldPassword
     * @param currentUserId
     */
    public void updatePhone(String newPhone, String oldPassword, String currentUserId) {
        Employee employee = employeeService.getById(currentUserId);
        ValidationUtils.throwIf(!DigestUtil.bcryptCheck(oldPassword,employee.getPassword()),"密码错误");
        ValidationUtils.throwIfNotNull(employeeService.getByPhone(newPhone),"该手机号已绑定其他账户");
        ValidationUtils.throwIfEqual(newPhone, employee.getMobilePhone(), "新手机号不能与当前手机号相同");
        employee.setMobilePhone(newPhone);
        employeeService.updateById(employee);

        log.info("更新员工个人电话成功, {}, {}", currentUserId, newPhone);
    }

    // Todo: 未完成
    public String updateAvatar(MultipartFile avatarFile, String currentUserId) {
        return null;
    }
}
